#!/usr/bin/env python3
"""
Prometheus 监控系统启动脚本
同时启动所有必要的服务组件
"""

import subprocess
import time
import threading
import signal
import sys
import os

class PrometheusLauncher:
    def __init__(self):
        self.processes = []
        self.running = True
    
    def start_service(self, name, command, delay=0):
        """启动单个服务"""
        if delay > 0:
            print(f"⏳ 等待 {delay} 秒后启动 {name}...")
            time.sleep(delay)
        
        print(f"🚀 启动 {name}...")
        try:
            process = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                preexec_fn=os.setsid
            )
            self.processes.append((name, process))
            print(f"✅ {name} 启动成功 (PID: {process.pid})")
            return process
        except Exception as e:
            print(f"❌ {name} 启动失败: {e}")
            return None
    
    def monitor_process(self, name, process):
        """监控进程状态"""
        while self.running:
            if process.poll() is not None:
                print(f"⚠️  {name} 进程已退出")
                break
            time.sleep(5)
    
    def start_all_services(self):
        """启动所有服务"""
        print("=" * 60)
        print("🎯 Prometheus 监控系统启动器")
        print("=" * 60)
        
        # 安装依赖
        print("📦 安装Python依赖...")
        subprocess.run([
            "pip", "install", "-q", 
            "requests", "pyyaml", "psutil"
        ], check=False)
        
        # 启动服务列表
        services = [
            {
                'name': 'Node Exporter (模拟)',
                'command': 'python3 mock_node_exporter.py',
                'delay': 0
            },
            {
                'name': 'Application (模拟)',
                'command': 'python3 mock_app.py',
                'delay': 2
            },
            {
                'name': 'Prometheus Server',
                'command': 'python3 prometheus_server.py',
                'delay': 5
            }
        ]
        
        # 启动所有服务
        for service in services:
            thread = threading.Thread(
                target=self.start_service,
                args=(service['name'], service['command'], service['delay']),
                daemon=True
            )
            thread.start()
        
        # 等待所有服务启动
        time.sleep(8)
        
        # 显示服务状态
        self.show_status()
        
        # 保持运行
        self.keep_running()
    
    def show_status(self):
        """显示服务状态"""
        print("\n" + "=" * 60)
        print("📊 服务状态")
        print("=" * 60)
        
        services_info = [
            {
                'name': 'Node Exporter',
                'url': 'http://localhost:9100/metrics',
                'description': '系统指标收集器'
            },
            {
                'name': 'Mock Application',
                'url': 'http://localhost:8080',
                'description': '模拟业务应用'
            },
            {
                'name': 'Application Metrics',
                'url': 'http://localhost:8080/metrics',
                'description': '应用指标端点'
            },
            {
                'name': 'Prometheus Server',
                'url': 'http://localhost:9090',
                'description': 'Prometheus Web界面'
            },
            {
                'name': 'Prometheus API',
                'url': 'http://localhost:9090/api/v1/targets',
                'description': 'Prometheus API'
            }
        ]
        
        for service in services_info:
            print(f"🌐 {service['name']:<20} {service['url']}")
            print(f"   {service['description']}")
            print()
        
        print("=" * 60)
        print("🎉 所有服务已启动完成!")
        print("💡 访问 http://localhost:9090 查看Prometheus监控界面")
        print("📱 访问 http://localhost:8080 查看模拟应用")
        print("📊 访问 http://localhost:9100/metrics 查看系统指标")
        print("=" * 60)
    
    def keep_running(self):
        """保持程序运行"""
        try:
            print("\n⌨️  按 Ctrl+C 停止所有服务")
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            self.shutdown()
    
    def shutdown(self):
        """关闭所有服务"""
        print("\n🛑 正在停止所有服务...")
        self.running = False
        
        for name, process in self.processes:
            try:
                print(f"⏹️  停止 {name}...")
                os.killpg(os.getpgid(process.pid), signal.SIGTERM)
                process.wait(timeout=5)
            except Exception as e:
                print(f"⚠️  停止 {name} 时出错: {e}")
        
        print("👋 所有服务已停止")
        sys.exit(0)

def main():
    launcher = PrometheusLauncher()
    
    # 注册信号处理器
    def signal_handler(sig, frame):
        launcher.shutdown()
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 启动所有服务
    launcher.start_all_services()

if __name__ == '__main__':
    main()